'use strict';

/* Controllers */
app.controller('houseOwnerLoanListCtl', function($scope,$compile,ngDialog,uiLoad,rest,$ocLazyLoad,$state,user,$http) {
    var rentTypeObj = {
        0: "年付",
        1: "季付",
        2: "月付"
    };
    var applyTypeObj = {
        0: "支付包",
        1: "微信",
        2: "现金"
    };
    $scope.checkType = {};
    $scope.checkStatus = {};
    $scope.decorateStatus = {};
    $scope.checkTypeArray = [{ "name": "全部", "value": -1 },
                             { "name": "未申请", "value": -2 },
                             { "name": "申请中", "value": 0 },
                             { "name": "申请成功", "value": 1 },
                             { "name": "申请失败", "value": 2 },
                             { "name": "补件", "value": 5 }];

    $scope.lockTypeArray = [{ "name": "全部", "value": -1 },
                            { "name": "未安装", "value": 0 },
                            { "name": "锁电安装中", "value": 3 },
                            { "name": "锁电安装成功", "value": 4 }];

    if($scope.queryParams){

    }
    $scope.queryParams = {
        'checkStatus': $scope.checkStatus.selected,
        'contractStartDate': $scope.contractStartDate,
        'contractEndDate': $scope.contractEndDate,
        'nameCode': $scope.nameCode
    }


    //监听浏览器大小变化
    // window.onresize = function(){
    //     window.location.reload();
    // }

    $scope.showApplyRent = function(){
        rest.java({
            url: '/decorate-service/decorate/api/service/getCreditLine.json',
            data: {
                originalId: user.get('openId'),
                // originalId: "b8bf8e32ca823088833d2f7a0ba1fae2",
            },
            success: function(res) {
                if( res.code == '0' ) {
                    //实际
                    $scope.receivedAmount = res.res.data.receivedAmount;
                    //申请中
                    $scope.applySumAmount = res.res.data.applySumAmount;
                    //可申请
                    $scope.availableCreditLine = res.res.data.availableCreditLine;
                    //最大
                    $scope.creditLine = res.res.data.creditLine;
                    $scope.$apply();
                } else {
                    //alert( res.res.msg )
                }
            },
            error: function() {

            }

        });
    }
    $scope.showApplyRent();

    $scope.$watch('nameCode', function(newValue, oldValue) {
        $scope.nameCode = newValue;
    });
    $scope.$on('contractDate.start', function(event, data) {
        $scope.contractStartDate = data ? (data + " 00:00:00") : "";
        // console.log(data);
    });
    $scope.$on('contractDate.end', function(event, data) {
        $scope.contractEndDate = data ? (data + " 00:00:00") : "";
        // console.log(data);
    });
    $scope.queryUser = function() {
        if($scope.queryParams.checkStatus && $scope.queryParams.checkStatus.selected){
            var checkStatusCache = $scope.queryParams.checkStatus.selected;
            if($scope.queryParams.checkStatus.selected){
                $scope.queryParams.checkStatus = $scope.queryParams.checkStatus.selected.value
            }
            $scope.queryParams = {
              //'checkStatus': $scope.checkStatus.selected,
                'contractStartDate': $scope.contractStartDate,
                'contractEndDate': $scope.contractEndDate,
                'nameCode': $scope.nameCode
            }
            console.log($scope.queryParams);
            $scope.dataTable.fnClearTable();
            $scope.queryParams.checkStatus = {};
            $scope.queryParams.checkStatus.selected = {};
            $scope.queryParams.checkStatus.selected = checkStatusCache;
        }else if($scope.queryParams.decorateStatus && $scope.queryParams.decorateStatus.selected){
            var decorateStatusCache = $scope.queryParams.decorateStatus.selected;
            if($scope.queryParams.decorateStatus.selected){
                $scope.queryParams.decorateStatus = $scope.queryParams.decorateStatus.selected.value
            }
            $scope.queryParams = {
              //'decorateStatus': $scope.decorateStatus.selected,
                'contractStartDate': $scope.contractStartDate,
                'contractEndDate': $scope.contractEndDate,
                'nameCode': $scope.nameCode
            }
            console.log($scope.queryParams);
            $scope.dataTable.fnClearTable();
            $scope.queryParams.decorateStatus = {};
            $scope.queryParams.decorateStatus.selected = {};
            $scope.queryParams.decorateStatus.selected = decorateStatusCache;
        }else{
            $scope.queryParams = {
               // 'checkStatus': $scope.decorateStatus.selected,
                'contractStartDate': $scope.contractStartDate,
                'contractEndDate': $scope.contractEndDate,
                'nameCode': $scope.nameCode
            }
            console.log($scope.queryParams);
            $scope.dataTable.fnClearTable();
        }
    };
    
    $scope.initDataTable = function(){
        $scope.tableLoanDatas = {
            "sAjaxSource": "4011",
            "dom": "tpr",
            "bAutoWidth": true,
            "aoColumns": [
            {
                "mDataProp": "index",
                "sTitle": "门锁ID",
                "sDefaultContent": "",
                "sClass": "center"
            },{
                "mDataProp": "cityName",
                "sTitle": "设备厂商",
                "sDefaultContent": "",
                "sClass": "center"
            },
            // {
            //     "mDataProp": "countyName",
            //     "sTitle": "区县",
            //     "sDefaultContent": "",
            //     "sClass": "center"
            // },
            {
                "mDataProp": "areaName",
                "sTitle": "小区",
                "sDefaultContent": "",
                "sClass": "center"
            }, {
                "mDataProp": "leaseType",
                "sTitle": "楼栋",
                "sDefaultContent": "",
                "sClass": "center"
            }, {
                "mDataProp": "houseType",
                "sTitle": "房间号",
                "sDefaultContent": "",
                "sClass": "center"
            }, {
                "mDataProp": "roomCode",
                "sTitle": "门牌号",
                "sDefaultContent": "",
                "sClass": "center"
            }, {
                "mDataProp": "houseRent",
                "sTitle": "绑定用户",
                "sDefaultContent": "",
                "sClass": "center"
            }, {
                "mDataProp": "payTypeName",
                "sTitle": "门锁电量",
                "sDefaultContent": "",
                "sClass": "center"
            }, {
                "mDataProp": "createDate",
                "sTitle": "门锁状态",
                "sDefaultContent": "",
                "sClass": "center"
            },
            // 小艳说：提现额度隐藏，以后要有一个提现额度总值
            // }, {
            //     "mDataProp": "assessAmount",
            //     "sTitle": "提现额度",
            //     "sDefaultContent": "",
            //     "sClass": "center"
            {
                "mDataProp": "operate",
                "sTitle": "操作",
                "sDefaultContent": "",
                "sClass": "center handle-td operation"
            }],
            "fnRowCallback": function(nRow, aData, iDisplayIndex) {
                var btnStr = "";
                var btnStr2 = "";
                var auditStr = "";
                if (null == aData.checkStatus || "-1" == aData.checkStatus) {
                    auditStr = "<div><div class='notApply-bj1'>未申请</div><div class='notApply-bj'></div></div>"
                }
                if ("0" == aData.checkStatus) {
                    auditStr = "<div><div class='rent-bj1'>申请中</div><div class='rent-bj'></div></div>"
                }
                if ("1" == aData.checkStatus) {
                    if (aData.decorateStatus == 4) {
                        auditStr = "<div><div class='confirmed-bj1'>锁电安装成功</div><div class='confirmed-bj status-num5'></div></div>"
                    }else if(aData.decorateStatus == 3){
                        auditStr = "<div><div class='rent-bj1'>锁电安装中</div><div class='lock-bj'></div></div>"
                    }else{
                        auditStr = "<div><div class='confirmed-bj1'>申请成功</div><div class='confirmed-bj status-num4'></div></div>"
                    }
                }
                if ("2" == aData.checkStatus) {
                    auditStr = "<div><div class='failure-bj1'>申请失败</div><div class='failure-bj status-num4'></div></div>"
                }
                if ("5" == aData.checkStatus) {
                    auditStr = "<div><div class='supplement-bj1'>补件中</div><div class='supplement-bj'></div></div>"
                }

                // 查看 一直在，始终能看
                //  btnStr = $('<div></div>').append(row_audit_staus(aData)).html();

                //  function row_audit_staus (data) {



                //     var sdom = $('<a></a>').addClass('operation-btn');
                //     var simg = $('<img>').attr({
                //         'src': 'img/operation.png',
                //         'width': '20px',
                //         'height': '20px'
                //     });
                //     var sdiv = $('<div></div>').addClass('operation-loan');
                //     var sdl = $('<dl></dl>').addClass('operation oper-triangle');
                //     var sdd = $('<dd></dd>');
                //     if (aData.checkStatus == "2") {
                //         var shref_1 = $('<a>修改</a>').attr({
                //             'ng-click':'decorateModify($event, \"' + aData.decorateId + '\")',
                //         });
                //     }else{
                //         var shref_1 = $('<a>查看</a>').attr({
                //             'ng-click':'decorateReview($event, \"' + aData.decorateId + '\")',
                //         });
                //     };
                //     var sdd_1 = $('<dd></dd>'),shref_2;
                //     if ("1" == aData.checkStatus && "0" == aData.decorateOrderStatus) {
                //             // 申请装修分期(灰)：装修评估申请中
                //         // shref_2 = $('<div>申请装修分期</div>');
                //     }else if("4" == aData.decorateStatus && "0" == aData.decorateOrderStatus) {
                //             // 申请装修分期：锁电安装完成
                //         shref_2 = $('<a>申请装修分期</a>').attr({
                //             'ng-click':'decorateWithdraw($event, \"" + aData.decorateId + "\")',
                //         });
                //     } else if("1" == aData.checkStatus && "0" == aData.decorateOrderStatus) {
                //            // 授信冻结(灰)：申请通过
                //         shref_2 = $('<div>授信冻结</div>');
                //     }else if("1" == aData.checkStatus && "0" == aData.decorateOrderStatus) {
                //            // 授信冻结(灰)：申请通过
                //         shref_2 = $('<div>授信冻结</div>');
                //     }else if("1" == aData.decorateOrderStatus) {
                //            // 分期业务申请中：（提现中）申请装修分期确认
                //         shref_2 = $('<div>分期业务申请中</div>');
                //     }else if("2" == aData.decorateOrderStatus) {
                //            // 分期业务申请中：（提现中）申请装修分期确认
                //         shref_2 = $('<div>申请通过</div>');
                //     }else {
                //         // 未知状态
                //     }
                //     var sdd_2 = $('<dd></dd>');
                //     var span = $('<span>◆</span>').addClass('z-1');
                //     var span_1 = $('<span>◆</span>').addClass('y-1');

                //     sdd_2.append(span_1).append(span)
                //     sdd_1.append(shref_2)
                //     sdd.append(shref_1)
                //     sdl.append(sdd).append(sdd_1).append(sdd_2)
                //     sdiv.append(sdl)
                //     sdom.append(simg).append(sdiv)
                //     return sdom;
                // }


                 //btnStr += "<a href='javascript:;' class='btn btn-yellow' style='margin-right:10px;' ng-click='decorateReview($event, \"" + aData.decorateId + "\")'>查看</a>";

                // 装修评估资料
                // 能改 2(申请不通过)
                // 不能改 0(申请中)，1(申请通过)

                if(aData.checkStatus == "-1" || aData.checkStatus == null){
                    btnStr += "<a href='javascript:;' class='btn btn-yellow' style='margin-right:10px;' ng-click='decorateDialog($event,\"" + aData.houseId + "\")'>申请</a>";
                }else if(aData.checkStatus == "0"){
                    btnStr += "<a href='javascript:;' class='btn btn-yellow' style='margin-right:10px;' ng-click='decorateReview($event, \"" + aData.decorateId + "\")'>查看</a>";
                }else if(aData.checkStatus == "1"){
                    if (aData.decorateStatus == 4) {
                        btnStr += "<a href='javascript:;' class='btn btn-yellow' style='margin-right:10px;' ng-click='decorateReview($event, \"" + aData.decorateId + "\")'>查看</a>";
                    }else if(aData.decorateStatus == 0){
                        btnStr += "<a href='javascript:;' class='btn btn-yellow' style='margin-right:10px;' ng-click='decorateReview($event, \"" + aData.decorateId + "\")'>查看</a>";
                        btnStr2 += "<a href='javascript:;' class='btn btn-yellow' style='margin-right:10px;' ng-click='lockerAndElec($event, \"" + aData.houseId + "\")'>锁电安装</a>";
                    }else{
                        btnStr += "<a href='javascript:;' class='btn btn-yellow' style='margin-right:10px;' ng-click='decorateReview($event, \"" + aData.decorateId + "\")'>查看</a>";
                    }
                }else if( aData.checkStatus == "2") {
                    btnStr += "<a href='javascript:;' class='btn btn-yellow' style='margin-right:10px;' ng-click='decorateReview($event, \"" + aData.decorateId + "\")'>查看</a>";
                }else if( aData.checkStatus == "5") {
                    btnStr += "<a href='javascript:;' class='btn btn-yellow' style='margin-right:10px;' ng-click='decorateModify($event, \"" + aData.decorateId + "\")'>补件</a>";
                } 
                // 装修分期
                // 申请装修分期(灰)：装修评估申请中
                // 授信冻结(灰)：申请通过
                // 申请装修分期：锁电安装完成
                // 分期业务申请中：（提现中）申请装修分期确认
                // 驳回：金融业务驳回

                // decorateOrderStatus
                // 0，平时，未进入分期业务申请
                // 1，表示分期业务申请中
                // 2，表示申请通过
                // 3，表示申请未通过
                // 4，表示还款中
                // 5，表示订单完结

                // if ("1" == aData.checkStatus && "0" == aData.decorateOrderStatus) {
                //     //申请装修分期(灰)：装修评估申请中
                //     btnStr += "<a href='javascript:;' class='btn btn-yellow disabled' style='margin-right:10px;'>申请装修分期</a>";
                // } else if ("4" == aData.decorateStatus && "0" == aData.decorateOrderStatus) {
                //     // 申请装修分期：锁电安装完成
                //     btnStr += "<a href='javascript:;' class='btn btn-yellow' style='margin-right:10px;' ng-click='decorateWithdraw($event, \"" + aData.decorateId + "\")'>申请装修分期</a>";
                // } else if ("1" == aData.checkStatus && "0" == aData.decorateOrderStatus) {
                //     // 授信冻结(灰)：申请通过
                //     btnStr += "<a href='javascript:;' class='btn btn-yellow disabled' style='margin-right:10px;'>授信冻结</a>";
                // } else if ("1" == aData.decorateOrderStatus) {
                //     // 分期业务申请中：（提现中）申请装修分期确认
                //     btnStr += "<a href='javascript:;' class='btn btn-yellow disabled' style='margin-right:10px;'>分期业务申请中</a>";
                // } else if ("2" == aData.decorateOrderStatus) {
                //     // 分期业务申请中：（提现中）申请装修分期确认
                //     btnStr += "<a href='javascript:;' class='btn btn-yellow disabled' style='margin-right:10px;'>申请通过</a>";
                // } else {
                //     // 未知状态
                //     btnStr += "";
                // }



                function time(mydate){
                  var str = mydate.substring(0,10);
                  var dataArr = str.split('-');
                  var timeStr = dataArr[0]
                    +"年"+dataArr[1]+"月"+dataArr[2]
                    +"日";
                    return timeStr;
                }
                if (aData.decorateStatus == 4) {
                    var installStatus1 = "已安装"; 
                }else{
                    var installStatus1 = "未安装";
                }
                // btnStr += "<a href='javascript:;' class='btn btn-yellow' ng-click='cancelReturnProOrder(" + aData.houseId + "," + aData.orderId +")' style='margin-right:10px;' >补件</a>";
                $(nRow).find(".handle-td").append($compile(btnStr)($scope));
                $(nRow).find(".handle-td").append($compile(btnStr2)($scope));
                $(nRow).find(".handle-td>a.operation-btn").on('click', function (e) {
                    e.preventDefault();
                    var sopt = $(this).parent().find(".operation-loan");
                    if (sopt.css('display') == 'none') {
                        $(".operation-loan").hide();
                        sopt.show();
                    } else {
                        sopt.hide();
                    }
                    return false;
                });
                if (aData.createDate != null && aData.checkDate != null) {
                    $(nRow).find(".submit-time").empty().append(time(aData.createDate));
                    $(nRow).find(".checkout-time").empty().append(time(aData.checkDate));
                }
                $(nRow).find(".audit").empty().append($compile(auditStr)($scope));
                $(nRow).find(".installStatus").empty().append(installStatus1);
                // console.log(aData);
                $scope.houseId = aData.houseId;
            },
            "fnDrawCallback": function(oSettings) {
                $scope.checkStatusValue = $scope.queryParams.checkStatus;
                if ("number" == typeof $scope.checkStatusValue) {
                    $scope.checkTypeArray.map(function(ele, index) {
                        if ($scope.checkStatusValue == ele.value) {
                            $scope.checkStatus.selected = ele;
                        }
                    })
                }

                $scope.decorateStatusValue = $scope.queryParams.decorateStatus;
                if ("number" == typeof $scope.decorateStatusValue) {
                    $scope.lockTypeArray.map(function(ele, index) {
                        if ($scope.decorateStatusValue == ele.value) {
                            $scope.decorateStatus.selected = ele;
                        }
                    })
                }
            },
            "fnServerParams": function(aoData) {
                if($scope.checkStatus && $scope.checkStatus.selected){
                    $scope.queryParams.checkStatus = $scope.checkStatus.selected.value
                }
                if($scope.decorateStatus && $scope.decorateStatus.selected){
                    $scope.queryParams.decorateStatus = $scope.decorateStatus.selected.value
                }
                aoData.push({
                    'name': 'queryParams',
                    'value': $scope.queryParams
                });
                return aoData;
            }
        };
    }

    $scope.initDataTable();

    $scope.dataTable = undefined;

    // $scope.decorateWithdraw = function (e, decorateId) {

    //     ngDialog.openConfirm({
    //       template: 'js/module/fund/confirmAgain.html',
    //       resolve: {
    //         load: function() {
    //             return uiLoad.load(['js/module/fund/confirmAgain.js'])
    //         }
    //       },
    //       data:{
    //         decorateId: decorateId
    //       },
    //       scope: $scope,
    //       width: 600,
    //       // height: 700
    //     }).then(null, function(reason) {
    //         if (reason && reason.clickOk) {
    //             var btn = $(e.target);
    //             btn.addClass('disabled');
    //             rest.post({
    //                 methodId: '4036',
    //                 data: {'decorateId': decorateId},
    //                 success: function(res) {
    //                     if (res.code == 0) {
    //                         btn.text('分期业务申请中');
    //                     } else {
    //                         btn.removeClass('disabled');
    //                     }
    //                 },
    //                 error: function() {
    //                     btn.removeClass('disabled');
    //                 }
    //             })
    //         }
    //     });
    // }
    //修改装修评估
    $scope.decorateModify = function (e, decorateId) {
        var btn = $(e.target);
        ngDialog.openConfirm({
          template: 'js/module/decorate/modify.html',
          resolve: {
            load: function() {
                return $ocLazyLoad.load('angularFileUpload').then(
                    function(){
                        return uiLoad.load(['js/module/decorate/modify.js'])
                    });
            }
          },
          data:{
            decorateId:decorateId
          },
          scope: $scope,
          width: 1200,
          // height: 700
        }).then(function(data) {
            $state.go('app.houseOwner.loanList');
            $scope.dataTable.fnClearTable();
        }, function(reason) {
            $state.go('app.houseOwner.loanList');
            $scope.dataTable.fnClearTable();
        });

    }
    //申请装修评估
    $scope.decorateDialog = function (e, houseId) {
        var btn = $(e.target);
        ngDialog.openConfirm({
          template: 'js/module/decorate/uploadPic.html',
          resolve: {
            load: function() {
                return $ocLazyLoad.load('angularFileUpload').then(
                    function(){
                        return uiLoad.load(['js/module/decorate/uploadPic.js'])
                     });
            }
          },
          data:{
            houseId:houseId
          },
          scope: $scope,
          width: 1200,
          // height: 700
        }).then(function(data) {
            // $scope.dataTable.fnClearTable();
            $scope.initDataTable();
            window.location.reload();
        }, function(reason) {
            // $scope.dataTable.fnClearTable();
            $scope.initDataTable();
            window.location.reload();
        });
    }
    //查看装修评估
    $scope.decorateReview = function (e, decorateId) {
        ngDialog.openConfirm({
          template: 'js/module/decorate/review.html',
          resolve: {
            load: function() {
                return $ocLazyLoad.load('angularFileUpload').then(
                    function(){
                        return uiLoad.load(['js/module/decorate/review.js'])
                    });
            }
          },
          data:{
            decorateId:decorateId
          },
          scope: $scope,
          width: 1200,
          // height: 700
        }).then(function(data) {

        }, function(reason) {

        });
    }
    //安装锁电
    $scope.lockerAndElec = function (e, houseId) {
        var btn = $(e.target);
        btn.addClass('disabled');
        rest.post({
            methodId: '4034',
            data: {'houseId': houseId},
            success: function(res) {
                if (res.code == 0) {
                    btn.text('锁电安装中');
                    // $scope.dataTable.fnClearTable();
                } else {
                    btn.removeClass('disabled');
                }
            },
            error: function() {
                btn.removeClass('disabled');
            }
        })

    }
    //申请放款
    $scope.applyLoan = function () {
        ngDialog.openConfirm({
          template: 'js/module/decorate/loans.html',
          resolve: {
            load: function() {
              return uiLoad.load(['js/module/decorate/loans.js'])
            }
          },
          data:{
            availableCreditLine: $scope.availableCreditLine,
          },
          scope: $scope,
          width: 600,
          // height: 700
        }).then(function(data) {
            $scope.showApplyRent();
        }, function(reason) {
            console.log('close it');
            $scope.showApplyRent();
        });
    }

    // 回调函数,返回实例化的jquery 插件对象
    $scope.initFinish = function(dataTable) {
        $scope.dataTable = dataTable;
    }
    $('#example thead').on('click', 'th', function() {
        // var data = $('#example').DataTable().row( this ).data();
        // alert('You clicked on  row');
    });
    $('#example tbody').on('click', 'span#edit', function() {
        var data = $('#example').DataTable().row($(this).parents('tr'));
        alert("查看修改：" + data[0]);
    });
    $('#example tbody').on('click', 'span#del', function() {
        // var data = $('#example').DataTable().row($(this).parents('tr')).data();
    });
});


app.controller('ContractTimeCtrl',function($scope){
  $scope.today = function() {
      $scope.contractStartDate = "";
      $scope.contractEndDate = "";
    };

    $scope.closeAll = function() {
      $scope.openContractBeginDated =
      $scope.openContractEndDated = false;
    }

    $scope.openContractBeginDate = function($event) {
      $event.preventDefault();$event.stopPropagation();$scope.closeAll();
      $scope.openContractBeginDated = true;
    };
    $scope.openContractEndDate = function($event) {
      $event.preventDefault();$event.stopPropagation();$scope.closeAll();
      $scope.openContractEndDated = true;
    };

    $scope.dateOptions = {
      format: 'yyyy/MM/dd',
      startingDay: 1,
      class: 'datepicker'
    };

    $scope.format = 'yyyy/MM/dd';

    $scope.today();

    $scope.$watch('contractStartDate',function(newValue,oldValue){
      if("[object Date]" === Object.prototype.toString.call(newValue)) {
         $scope.$emit('contractDate.start',moment(newValue).format('YYYY/MM/DD'))
      } else if (null === newValue) {
        $scope.$emit('contractDate.start','')
      }
    });
    $scope.$watch('contractEndDate',function(newValue,oldValue){
      if("[object Date]" === Object.prototype.toString.call(newValue)) {
         $scope.$emit('contractDate.end',moment(newValue).format('YYYY/MM/DD'))
      } else if (null === newValue) {
        $scope.$emit('contractDate.end','')
      }
    });
});
